package com.timeshare.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.timeshare.common.Result;
import com.timeshare.dto.SkillVO;
import com.timeshare.entity.User;
import com.timeshare.service.UserService;
import com.timeshare.service.SkillService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理后台控制器
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    
    private final UserService userService;
    private final SkillService skillService;
    
    public AdminController(UserService userService, SkillService skillService) {
        this.userService = userService;
        this.skillService = skillService;
    }
    
    /**
     * 验证管理员权限
     */
    private void checkAdminRole(Long userId) {
        User user = userService.getById(userId);
        if (user == null || user.getRole() != 1) {
            throw new RuntimeException("无权访问");
        }
    }
    
    /**
     * 获取用户列表
     */
    @GetMapping("/users")
    public Result<Page<User>> getUserList(
            Authentication authentication,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String keyword) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            Page<User> users = userService.getUserList(page, size, keyword);
            return Result.success(users);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 封禁用户
     */
    @PostMapping("/users/{id}/ban")
    public Result<String> banUser(Authentication authentication, @PathVariable Long id) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            userService.banUser(id);
            return Result.success("封禁成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 解封用户
     */
    @PostMapping("/users/{id}/unban")
    public Result<String> unbanUser(Authentication authentication, @PathVariable Long id) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            userService.unbanUser(id);
            return Result.success("解封成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取待审核技能列表
     */
    @GetMapping("/skills/pending")
    public Result<Page<SkillVO>> getPendingSkills(
            Authentication authentication,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            Page<SkillVO> skills = skillService.getPendingSkills(page, size);
            return Result.success(skills);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 审核通过技能
     */
    @PostMapping("/skills/{id}/approve")
    public Result<String> approveSkill(Authentication authentication, @PathVariable Long id) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            skillService.approveSkill(id);
            return Result.success("审核通过");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 拒绝技能
     */
    @PostMapping("/skills/{id}/reject")
    public Result<String> rejectSkill(
            Authentication authentication,
            @PathVariable Long id,
            @RequestParam String reason) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            skillService.rejectSkill(id, reason);
            return Result.success("已拒绝");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取统计数据
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics(Authentication authentication) {
        try {
            Long userId = (Long) authentication.getPrincipal();
            checkAdminRole(userId);
            
            Map<String, Object> statistics = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.count();
            long activeUsers = userService.count(new LambdaQueryWrapper<User>().eq(User::getStatus, 0));
            long bannedUsers = userService.count(new LambdaQueryWrapper<User>().eq(User::getStatus, 1));
            
            Map<String, Object> userStats = new HashMap<>();
            userStats.put("total", totalUsers);
            userStats.put("active", activeUsers);
            userStats.put("banned", bannedUsers);
            statistics.put("users", userStats);
            
            // 技能统计
            long totalSkills = skillService.count();
            long publishedSkills = skillService.count(new LambdaQueryWrapper<com.timeshare.entity.Skill>().eq(com.timeshare.entity.Skill::getStatus, 1));
            long pendingSkills = skillService.count(new LambdaQueryWrapper<com.timeshare.entity.Skill>().eq(com.timeshare.entity.Skill::getStatus, 0));
            
            Map<String, Object> skillStats = new HashMap<>();
            skillStats.put("total", totalSkills);
            skillStats.put("published", publishedSkills);
            skillStats.put("pending", pendingSkills);
            statistics.put("skills", skillStats);
            
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}

